package com.buli.blmall.admin.common.controller;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @className: ImageController
 * @author: Xiang.Gao
 * @date: 2025/11/12
 * @description:
 */
@RequestMapping("image")
@RestController
public class ImageController {

    /**
     * 接收图片，处理后返回结果图片
     *
     * @param image 上传的图片文件
     * @return 处理后的图片
     */
    @PostMapping("/resize")
    public ResponseEntity<byte[]> resize(@RequestParam("image") MultipartFile image,
                                         @RequestParam(value = "scale", defaultValue = "1.0" ) float scale,
                                         @RequestParam(value = "formatter", defaultValue = "jpg") String format) {
        try {
            // 检查文件是否为空
            if (image.isEmpty()) {
                return ResponseEntity.badRequest().build();
            }

            // 获取原始图片字节数据
            byte[] originalImageData = image.getBytes();

            // 示例：调用图片处理服务
            byte[] processedImageData = processImageLogic(originalImageData, scale, format);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();

            // 设置下载文件名
            MediaType mediaType = getMediaTypeByFormat(format);
            String filename = "resize_" + getBaseName(image.getOriginalFilename()) + "." + format;
            headers.setContentType(mediaType);
            headers.setContentDispositionFormData("attachment", filename);

            return new ResponseEntity<>(processedImageData, headers, HttpStatus.OK);

        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 图片处理逻辑 - 需要根据具体需求实现
     *
     * @param imageData 原始图片数据
     * @return 处理后的图片数据
     */
    private byte[] processImageLogic(byte[] imageData, float scale, String format) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        Thumbnails.of(new ByteArrayInputStream(imageData))
                // .width(2400).keepAspectRatio(true)
                .scale(scale)
                .outputQuality(1.0)
                .outputFormat(format)
                .toOutputStream(outputStream);
        return outputStream.toByteArray();
    }

    // 获取文件基础名称（不含扩展名）
    private String getBaseName(String filename) {
        if (filename == null || filename.isEmpty()) {
            return "image";
        }
        int dotIndex = filename.lastIndexOf('.');
        return dotIndex > 0 ? filename.substring(0, dotIndex) : filename;
    }

    // 根据格式获取对应的 MediaType
    private MediaType getMediaTypeByFormat(String format) {
        switch (format.toLowerCase()) {
            case "png":
                return MediaType.IMAGE_PNG;
            case "gif":
                return MediaType.IMAGE_GIF;
            case "webp":
                // 手动创建 webp 的 MediaType
                return new MediaType("image", "webp");
            case "jpg":
            case "jpeg":
            default:
                return MediaType.IMAGE_JPEG;
        }
    }

}
